﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using Director.ViewModels;
using Xceed.Wpf.AvalonDock.Layout.Serialization;

namespace Director
{
	public partial class MainWindow : Window
	{
		private readonly MainVM _mainVM;
		private readonly NotifyIcon _notifyIcon = new NotifyIcon(); 

		public MainWindow()
		{
			Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");

			InitializeComponent();
			DataContext = _mainVM = new MainVM(this);
			_mainVM.View = this;

			Loaded += (sender, args) => _mainVM.Init(dockManager);

			_notifyIcon.Icon = Debugger.IsAttached?Properties.Resources.Rafael:Properties.Resources.Donatelo;
			_notifyIcon.DoubleClick += (sender, args) => Visibility = Visibility.Visible;
			_notifyIcon.ContextMenu = new ContextMenu(new[] { new MenuItem("Close", ClosePlease) });
			_notifyIcon.Visible = true;

			_mainVM.UpdateNotify = UpdateNotify;
			_mainVM.ShowBalloon = ShowBalloon;
		}

		private void UpdateNotify(string s)
		{
			_notifyIcon.Text = s;
		}

		private void ShowBalloon(string title, string s)
		{
			_notifyIcon.ShowBalloonTip((int)TimeSpan.FromSeconds(2).TotalMilliseconds,title, s,ToolTipIcon.Info);
		}

		public bool CloseItPlease { get; private set; }

		private void ClosePlease(object sender, EventArgs e)
		{
			_notifyIcon.Visible = false;
			CloseItPlease = true;
			Close();
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			if (!CloseItPlease)
			{
				e.Cancel = true;
				Visibility = Visibility.Collapsed;
				return;
			}

			_mainVM.Dispose();
			var layoutSerializer = new XmlLayoutSerializer(dockManager);
			layoutSerializer.Serialize(@".\AvalonDock.Layout.config");
			base.OnClosing(e);
		}

		static List<object> _initialized = new List<object>();

		public void Connected()
		{
			var layoutSerializer = new XmlLayoutSerializer(dockManager);
			layoutSerializer.LayoutSerializationCallback += (s, e) =>
			{
				var abstractPaneVM = _mainVM.GetPaneVM(e.Model.ContentId);
				if (_initialized.Contains(abstractPaneVM)) return;
				_initialized.Add(abstractPaneVM);
				abstractPaneVM.Init();
				e.Content = abstractPaneVM;
				e.Model.Closed += abstractPaneVM.Closed;
				e.Model.IsActiveChanged += abstractPaneVM.IsActiveChanged;
			};
			layoutSerializer.Deserialize(@".\AvalonDock.Layout.config");
		}

		public void Disconnected()
		{
			var layoutSerializer = new XmlLayoutSerializer(dockManager);
			layoutSerializer.Serialize(@".\AvalonDock.Layout.config");
		}
	}
}
